package com.wodan.zhongjinjicang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wodan.zhongjinjicang.common.exception.BusinessException;
import com.wodan.zhongjinjicang.common.redis.JedisClient;
import com.wodan.zhongjinjicang.common.utils.JsonUtils;
import com.wodan.zhongjinjicang.common.utils.PasswordDes;
import com.wodan.zhongjinjicang.enums.BusinessErrorEnum;
import com.wodan.zhongjinjicang.frame.AbstractClientApiJsonBusinessMethodService;
import com.wodan.zhongjinjicang.mapper.UserMapper;
import com.wodan.zhongjinjicang.model.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 用户登录
 */
@Service("login")
public class UserLoginService extends AbstractClientApiJsonBusinessMethodService {


    private static final String PHONE = "phone";
    private static final String PASSWORD = "password";

    @Autowired
    private JedisClient jedisClient;

    @Value("${REDIS_USER_SESSION_KEY}")
    private String REDIS_USER_SESSION_KEY;
    @Value("${SSO_SESSION_EXPIRE}")
    private Integer SSO_SESSION_EXPIRE;

    @Autowired
    private UserMapper userDao;


    @Override
    protected JSONObject doExecute(JSONObject data,String sessionId) {

        UserBean userBean = JsonUtils.jsonToPojo(data.toJSONString(), UserBean.class);

        UserBean tuser = userDao.selectByPhone(userBean.getPhone());
        //校验密码
        if(null!=tuser && validatePwd(userBean.getPassword(), tuser.getPassword())){
            Map<String , Object> modelMap = new HashMap<String , Object>();
            modelMap.put("sessionId", createSession(tuser));
            modelMap.put("userInfo", tuser);
            return new JSONObject(modelMap);
        }else{
            throw new BusinessException(BusinessErrorEnum.ERROR.getCode(), "用户或密码错误");
        }

    }

    /**
     * 将用户会话信息保存至redis中并返回sessionId
     * @param tuser
     * @return
     */
    private String createSession(UserBean tuser) {
        //生成sessionId
        String sessionId = UUID.randomUUID().toString();
        //保存用户之前，把用户对象中的密码清空。
        tuser.setPassword("");
        //把用户信息写入redis
        jedisClient.set(REDIS_USER_SESSION_KEY + ":" + sessionId, JsonUtils.objectToJson(tuser));
        //设置session的过期时间:30分钟
        jedisClient.expire(REDIS_USER_SESSION_KEY + ":" + sessionId, SSO_SESSION_EXPIRE);
        return sessionId;
    }

    private boolean validatePwd(String pwd, String pwdMD5) {
        return pwd!=null&&pwdMD5!=null&&PasswordDes.makeMD5(pwd).equals(pwdMD5);
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected String[] getRequiredParams() {
        return new String[]{PHONE,PASSWORD};
    }

}
